// deviceList.js
const app = getApp()
var util = require('../../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    changeIntoIdentification: '',//转入人身份证号
    deviceList: [],
    hiddenmodalput: true,//可以通过hidden是否掩藏弹出框的属性，来指定那个弹出框
    thatIndex: 0,
    device: {},
    payData: {
      openid: wx.getStorageSync('openid'),
      total_fee:110000,
      body: "上户手续费"
    },
    wxUser:'',//转入人的微信id
    changeIntoRegisterName:'',//转入人的姓名
    registerName:'',//转出人姓名
    messagePushUrl: '', //消息推送pai的url
    showModalStatus: false
  },
  addDdevice: function (e) {
    wx.navigateTo({
      url: '/page-wode/deviceInformation/deviceInformation'
    })
  },
  buttonShow: function (e) {
    var that = this;
    var thatIndex = parseInt(e.currentTarget.id);
    that.setData({
      device: that.data.deviceList[thatIndex]
    })
    wx.showActionSheet({
      itemList: ['设备登记', '设备转移', '金融', '保险'],
      success: function (res) {
        var tpx = res.tapIndex;
        var factoryNum = that.data.device.factoryNum;
        var identification = wx.getStorageSync("identification");
        if (tpx == 0) {
          wx.showModal({
            title: '登记手续费',
            content: '是否支付此费用',
            success: function (res) {
              if (res.confirm) {
                wx.request({
                  url: app.globalData.requestURL +'registerLicense/selectTransforRegister',//等查询上户表的接口
                  method: 'GET',
                  data: {
                    factoryNum: factoryNum,
                    identification: identification,
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  success: function (resf) {
                    if (resf.data.status == '0') {//没有弹是否支付
                      that.wxPay();
                    } else if (resf.data.status == '1') {
                      wx.showToast({
                        title: '此设备已登记',
                        icon: 'loading',
                        duration: 2500,
                        mask: true
                      });
                    }
                  }
                })
              } else if (res.cancel) {
                //console.log('用户点击取消')
              }
            }
          })
        } else if (tpx == 1) {
          //显示输入身份证的框
          that.setData({
            showModalStatus: true
          })
        } else if (tpx == 2) {
          //金融
        } else if (tpx == 3) {
          //保险
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  changeIntoIdentification: function (e) {
    var that = this;
    that.setData({
      changeIntoIdentification: e.detail.value,
      registerName: wx.getStorageSync("registerName")
    });
    var changeIntoIdentification = that.data.changeIntoIdentification;
    var identification = wx.getStorageSync("identification");
    if (identification != changeIntoIdentification && changeIntoIdentification != "") {
      wx.request({
        url: app.globalData.requestURL +'userInfo/' + changeIntoIdentification + '/getUserInfoByCondition',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.status == '0' && res.data.data != null) {
            var changeIntoRegisterName = res.data.data[0].registerName;
            var len = changeIntoRegisterName.length - 1;
            var xing = '';
            for (var i = 0; i < len; i++) {
              xing += '*';
            }
            that.setData({
              hiddenmodalput: true,
              wxUser: res.data.data[0].wxUser,
              changeIntoRegisterName : changeIntoRegisterName.substring(0, 1) + xing
            });
          } else {
            wx.showToast({
              title: '提醒转入人注册或重新添加转入人',
              icon: 'loading',
              duration: 2500,
              mask: true,
              success: function () {
                that.setData({
                  hiddenmodalput: false
                });
              } //接口调用成功的回调函数
            });
          }
        }
      })
    } else if (identification == changeIntoIdentification || changeIntoIdentification == "") {
      wx.showToast({
        title: '转入人错误',
        icon: 'loading',
        duration: 2500,
        mask: true
      })
    }

  },
  searchDeviceInfo: function (e) {
    var that = this;
    var thatIndex = parseInt(e.currentTarget.id);
    that.setData({
      device: that.data.deviceList[thatIndex]
    })
    wx.setStorageSync("factoryNum", that.data.device.factoryNum)
    wx.navigateTo({
      url: '/page-deviceInfo/deviceInfo'
    })
  },
  /**
   * 设备转移的消息推送
   */
  messagePull:function(e){
    var that = this;
    var changeIntoIdentification = that.data.changeIntoIdentification;
    if (changeIntoIdentification != ''){
      var formId = e.detail.formId;
      var identification = wx.getStorageSync("identification");//转出单位
      var changeIntoRegisterName = that.data.changeIntoRegisterName;//转入单位
      var wxUser = that.data.wxUser; //接收消息的用户
      var machineryType = that.data.device.machineryType; //设备类型
      var deviecBrand = that.data.device.deviecBrand; //设备品牌
      var plateSubject = that.data.device.plateSubject; //设备型号
      var registerName = that.data.registerName; //转出人姓名
      var factoryNum = that.data.device.factoryNum; //设备大架号
      var pushParam = '{"factoryNum":"' + factoryNum + '","identification":"' + identification + '","changeIntoIdentification":"' + changeIntoIdentification + '"}';//推送消息跳转的页面的参数
      var date = new Date();
      var Y = date.getFullYear();//年 
      //月  
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      //日  
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      //时  
      var h = date.getHours();
      //分  
      var m = (date.getMinutes() < 10 ? +date.getMinutes() : date.getMinutes());
      that.setData({
        showModalStatus: false
      })
      var content = JSON.stringify([{
        keyword1: { //申请人
          value: registerName,
          color: "#173177"
        }
      },
      {
        keyword2: {//详情
          value: registerName + "的" + deviecBrand + plateSubject + machineryType + "设备将转入贵单位名下请您核对信息并完成此设备转入手续",
          color: "#173177"
        }
      },
      {
        keyword3: {//时间
          value: Y + "年" + M + "月" + D + "日 " + h + ":" + m,
          color: "#173177"
        }
      }]);
      wx.request({
        url: app.globalData.requestURL + 'wxMessage/pushMessage',//发送模版消息
        //
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          touser: wxUser,//接收消息的用户
          template_id: "_-dTL2OwXZJDsRDymy4I4K3HS2-v-GH27pQyV-_jWw4",
          page: "/page-receiveMessage/receiveMessage?pushParam=" + pushParam,
          form_id: formId,
          content, content
          //emphasis_keyword: "keyword1.DATA"
        },
        success: function (resmsg) {
          
          var errcode = resmsg.data.data.errcode
          // console.log("消息推送的返回值 " + errcode)
          if (errcode == 0 || errcode == '0') {
            wx.showToast({
              title: '通知已发出',
              icon: 'success',
              duration: 2000,
              mask: true
            });
          }
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({
      identification: wx.getStorageSync("identification")
    })
    var identification = that.data.identification;
    wx.request({
      url: 'https://www.gcjxglzx.com/deviceInformation/' + identification + '/getDeviceInformationByCondition',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' //默认值
      },
      success: function (res) {
        if (res.data.data != null) {
          for (var i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].machineryType == '1') {
              res.data.data[i].machineryType = "挖掘机"
            }
            if (res.data.data[i].machineryType == '2') {
              res.data.data[i].machineryType = "装载机"
            }
            if (res.data.data[i].machineryType == '3') {
              res.data.data[i].machineryType = "矿用自卸车"
            }
            if (res.data.data[i].machineryType == '4') {
              res.data.data[i].machineryType = "推土机"
            }
            if (res.data.data[i].machineryType == '5') {
              res.data.data[i].machineryType = "压路机"
            }
            if (res.data.data[i].machineryType == '6') {
              res.data.data[i].machineryType = "平地机"
            }
            if (res.data.data[i].machineryType == '7') {
              res.data.data[i].machineryType = "混凝土机械"
            }
            if (res.data.data[i].machineryType == '8') {
              res.data.data[i].machineryType = "桩工机械"
            }
            if (res.data.data[i].machineryType == '9') {
              res.data.data[i].machineryType = "凿岩机械"
            }
          }
          if (res.data.data != null && res.data.data.length > 0) {
            that.setData({
              deviceList: res.data.data
            });
          }
        }
      }
    })
  },
  wxPay: function () {
    var that = this;
    var prepayId;
    app.wxPay(that.data.payData);
    app.prepay_idReadyCallback = prepay_id => {
      prepayId = prepay_id
    }
    app.signReadyCallback = sign => {
      that.requestPayment(sign, prepayId,);
    }
  },
  //申请支付
  requestPayment: function (obj, prepayId) {
    var that = this;
    var data = obj;
    var openid = that.data.payData.openid
    var prepay_id = prepayId
    var factoryNum = that.data.device.factoryNum;
    var identification = wx.getStorageSync("identification");
    var template_id = "_ljZUx_3qM0BO6zdNehX5n98aiVrILPWOjagF-SBtgg";
    var machineryType = that.data.device.machineryType; //设备类型
    var deviecBrand = that.data.device.deviecBrand; //设备品牌
    var plateSubject = that.data.device.plateSubject; //设备型号
    var date = new Date();
    var Y = date.getFullYear();//年 
    //月  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日  
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    //时  
    var h = date.getHours();
    //分  
    var m = (date.getMinutes() < 10 ? +date.getMinutes() : date.getMinutes());
    console.log("当前时间是：" + Y + "年" + M + "月" + D + "日 " + h + ":" + m);
    that.setData({
      showModalStatus: false
    })
    var content = JSON.stringify([{
      keyword1: {//详情
        value: '贵单位的出场编号为"' + factoryNum + '"的' + deviecBrand + '牌' + plateSubject + machineryType + '设备已支付成功登记手续费！我单位工作人员将与您尽快联系请保持通讯畅通',
        color: "#173177"
      }
    },
    {
      keyword2: {//时间
        value: Y + "年" + M + "月" + D + "日 " + h + ":" + m,
        color: "#173177"
      }
    },
    {
      keyword3: {//金额
        value: that.data.payData.total_fee/100 +'元',
        color: "#173177"
      }
    }]);
    wx.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': data.signType,
      'paySign': data.paySign,
      'success': function (res) {
        //给设备主人发送消息推送
        wx.request({
          url: app.globalData.requestURL + 'wxMessage/pushMessage',//发送模版消息
          //
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            touser: openid,//接收消息的用户
            template_id: template_id,
            page: "/pages/index/index",
            form_id: prepay_id,
            content, content
            //emphasis_keyword: "keyword1.DATA"
          },
          success: function (resmsg) {
          }
        })

        //创建登记表
        wx.request({
          url: 'https://www.gcjxglzx.com/registerLicense/save',
          method: 'POST',
          data: {
            factoryNum: factoryNum,
            identification: identification,
            state: '0'
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (resp) {
            if (resp.data.status == '0') {
              wx.showToast({
                title: '登记成功！',
                icon: 'success',
                duration: 2000,
                mask: true,
                success: function () {
                  wx.redirectTo({
                    url: '/page-wode/deviceInformation/deviceList/deviceList'
                  })
                }
              });
            } else {
              wx.showToast({
                title: '登记失败！',
                icon: 'loading',
                duration: 2000,
                mask: true
              });
            }
          }
        })
      },
      'fail': function (res) {
        wx.showToast({
          title: '登记失败哦！',
          icon: 'loading',
          duration: 1500,
          mask: true
        });
      }
    })
  },







  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200,  //动画时长  
      timingFunction: "linear", //线性  
      delay: 0  //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      this.setData(
        {
          showModalStatus: true
        }
      );
    }
  }
})